package com.test.practice.collection.iterator;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

/**
 * 迭代器 Demo
 *
 * @Description: 迭代器 Demo
 * =======================
 * @Author: Jovi
 * =======================
 * @Date: Created in 2023-02-08
 * =======================
 * @Version: 1.1.2.0
 */
public class IteratorDemo {

    public static void main(String[] args) {

//        m1();

//        m2();

//        normalRemove();

        wrongRemove();

    }

    /**
     * 错误的Remove：不调用next()直接remove---.IllegalStateException
     */
    private static void wrongRemove() {
        Collection coll = new ArrayList();
        coll.add("123");
        coll.add(true);
        coll.add(456);
        coll.add(0.322);

        Iterator iterator = coll.iterator();
        while (iterator.hasNext()) {
            iterator.remove();
        }
    }


    private static void normalRemove() {
        Collection coll = new ArrayList();
        coll.add("123");
        coll.add(true);
        coll.add(456);
        coll.add(0.322);

        Iterator iterator = coll.iterator();
        while (iterator.hasNext()) {
            Object next = iterator.next();
            if (next.equals(456)) {
                iterator.remove();
            }
        }

        Iterator iterator1 = coll.iterator();
        while (iterator1.hasNext()) {
            System.out.println("new " + iterator1.next());
        }

        //这里hasNext=false是因为在上面的已经指针指到最后一个了
        while (iterator.hasNext()) {
            System.out.println("old " + iterator);
        }
    }

    /**
     * 错误迭代的两种方式
     */
    private static void m2() {
        Collection coll = new ArrayList();
        coll.add("123");
        coll.add(true);
        coll.add(456);
        coll.add(0.322);


        //错误方式1
//        Iterator iterator = coll.iterator();
//        while (iterator.next() != null) {
//            System.out.println(iterator.next());
//        }

        /**
         * 错误方式2，每调用一次coll.iterator()都会new一个新的对象，每个新的对象
         * 的hasNext()都是true，而且next()都是第一个元素
         */
//        while (coll.iterator().hasNext()) {
//            System.out.println(coll.iterator().next());
//        }
    }

    private static void m1() {
        Collection coll = new ArrayList();
        coll.add("123");
        coll.add(true);
        coll.add(456);
        coll.add(0.322);

        System.out.println("size:\t" + coll.size());

        Iterator iterator = coll.iterator();

        //不推荐
//        System.out.println(iterator.next());
//        System.out.println(iterator.next());
//        System.out.println(iterator.next());
//        System.out.println(iterator.next());
//        System.out.println(iterator.next()); //.NoSuchElementException

        //推荐
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }
}
